package cn.woochen.mvvmframe.activity

import android.content.Context
import android.content.Intent
import android.os.Build
import android.view.View
import android.webkit.WebView
import cn.woochen.comlib.jsbridge.OnBridgeCallback
import cn.woochen.comlib.jsbridge.WebViewHelper
import cn.woochen.comlib.util.ext.woochenLog
import cn.woochen.mvvmframe.R
import cn.woochen.mvvmframe.config.BaseActivity
import cn.woochen.mvvmframe.databinding.ActivityWebViewBinding
import cn.woochen.mvvmframe.viewmodels.EmptyViewModel
import cn.woochen.mvvmframe.web.MainJavascriptInterface

/**
 *类描述：webview与H5交互测试
 *@author woochen
 *@time 2021/7/30 10:39
 */
class WebViewActivity : BaseActivity<ActivityWebViewBinding, EmptyViewModel>(),
    View.OnClickListener {

    private val mWebViewHelper by lazy {
        WebViewHelper(this,mBinding.webView)
    }

    override fun setContentView(): Int = R.layout.activity_web_view

    override fun initData() {
        initWidgets()
        initListeners()
    }

    private fun initListeners() {
        mBinding.btnInvokeJs.setOnClickListener(this)
        mBinding.btnInvokeJs1.setOnClickListener(this)
    }

    companion object {
        fun start(context: Context) {
            val intent = Intent(context, WebViewActivity::class.java)
            context.startActivity(intent)
        }
    }

    private fun initWidgets() {
        mWebViewHelper.configSetting({
            mBinding.webView.addJavascriptInterface(MainJavascriptInterface(mWebViewHelper.responseCallbacks,mWebViewHelper), "android")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //js调试开关
                WebView.setWebContentsDebuggingEnabled(true)
            }
        })
        mWebViewHelper.loadUrl("file:///android_asset/demo.html")
    }

    override fun onClick(v: View?) {
        when (v) {
            mBinding.btnInvokeJs -> { //原生直接调用默认js方法
                /* native向js发送消息，js处理完后交给native(js注册方法->native调用->native注册方法(接收回调数据)->js调用)
                 * 1.加载本地js文件(js初始化)
                 * 2.native发送消息(调用js方法)
                 * 3.如果调用js方法时传递了callback_id,js方法执行完逻辑后调用native的方法(发送回调数据);否则直接结束
                 */
                mWebViewHelper.send(null, "[send]hello web_init!", object : OnBridgeCallback {
                    override fun onCallBack(data: String?) {
                        mBinding.tvContent.text = "[response]$data"
                    }
                })
            }
            mBinding.btnInvokeJs1 -> { //原生直接调用自定义js方法
                woochenLog("mBinding.btnInvokeJs1...")
                mWebViewHelper.send("functionInJs", "[send]hello web_functionInJs!", object :
                    OnBridgeCallback {
                    override fun onCallBack(data: String?) {
                        mBinding.tvContent.text = "[response]$data"
                    }
                })
            }

        }
    }
}